<?php

namespace App\Http\Controllers\Pay;

use App\Events\NotifyEvent;
use App\Helpers\PayTrait;
use App\Helpers\Wallet;
use App\Http\Controllers\Controller;
use App\Models\PayLog;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;
use Modules\Manager\Entities\Manager;
use Modules\Manager\Entities\Department;
use App\Http\Controllers\Wx\SendTemplateController;
use Illuminate\Http\Request;
use App\Models\Car\ReimburseDetail;

class PayNotifyController extends Controller
{
    use PayTrait,Wallet;
    protected $payType;
    public function webWxPay(){
        $config = config('pay');
        Pay::config($config);
        // 是的，你没有看错，就是这么简单！
        $result = Pay::wechat()->callback();
        $success = $result->get('summary');
        if($success=='支付成功') {
            $resource = $result->get('resource');
            $data = $resource['ciphertext'];
            $order_sn = $data['out_trade_no'];
            $trade_no = $data['transaction_id'];
            $amount = $data['amount']['total']/100;
            if ($order_sn) {
                $order = $this->getOrder($order_sn);
                if($order){
                    DB::transaction(function () use($trade_no,$order_sn,$order,$amount){
                        DB::update('update car_orders set mini_pay = ?, status = ?,out_trade_no = ?,fact_pay=? where order_sn = ? and status = ?',
                            [$amount,1,$trade_no,$amount,$order_sn,0]);
                    });
                    //付款成功通知（公众号）
                    $manager = Manager::query()->where('department_id',$order->department)->where('post_id',2)->first();
                    $departmentInfo = Department::query()->where('id',$order->department)->first();
                    if ($manager&&$manager['wechat_openid']) {
                        $tempmsg = [
                            'wechat_openid'=>$manager['wechat_openid'],
                            'orderType'=>'新订单提醒: '.$departmentInfo['name'].'店有新的订单，请及时联系客户',
                            'customerInfo'=>$order->customer_name||$order->wx_name,
                            'page'=>'pages/admin/home/home',
                        ];
                        (new SendTemplateController())->sendTemplateNewOrder($tempmsg);
                        info(json_encode($tempmsg));
                    }
                    $this->successPayLog(round($amount,2),$order);
                    event(new NotifyEvent($order,config('wechat.notify.mini.TradeSuccess')));
                }

            }
        }

        return Pay::wechat()->success();
    }
    public function webShopPay(Request $request){
        $input = $request->all();
        info($input);
        $config = config('pay');
        Pay::config($config);
        // 是的，你没有看错，就是这么简单！
        $result = Pay::wechat()->callback();
        info($result);
        $success = $result->get('summary');
        if($success=='商家转账批次完成通知') {
            $resource = $result->get('resource');
            $data = $resource['ciphertext'];
            $out_batch_no = $data['out_batch_no'];
            $batch_status = $data['batch_status'];
            if($batch_status=='FINISHED'){
                // 找到当前报销记录关联的报销项目-按项目内容进行报销
                $contents = ReimburseDetail::query()->where('out_batch_no',$out_batch_no)->get();
                foreach ($contents as $v){
                    // 找到单个项目记录
                    $item = ReimburseDetail::query()->where('id',$v->id)->first();
                    if ($v->user_type==1) {
                        // 员工报销
                        $user = Manager::query()->where('id',$v->user_id)->first();
                    }
                    if ($user&&$user['wechat_openid']) {
                        // 需要发送公众号消息推送：报销成功-发送给报销对象
                        $msg = [
                            'openid'=>$user['wechat_openid'],
                            'order_sn'=>$item->order_sn,
                            'status'=>4,
                            'type'=>$item->type,
                            'money'=>$item->money,
                            'page'=>'pages/admin/reimburse/reimburse?status=4',
                        ];
                        (new SendTemplateController())->sendTemplateBx($msg);
                        info(json_encode($msg));
                        // 打款成功后-更新为报销成功
                        $item->payment_at = now(); // 商户号打款成功时间
                        $item->save();
                    }
                }
            }
        }
        // $array = [
        //     'code' => 'SUCCESS',
        //     'message' => 'OK',
        // ];
        
        // $xmlString = $this->arrayToXml($array);
        // info($xmlString);
        // return $xmlString;
        // return response($xmlString,200)->header('Content-Type','text/xml');
        return response(200);
    }
    //更新支付日志记录
    public function successPayLog($realpay,$order){
        $data=[
            'real_pay'=>$realpay,
            'status'=>1,
        ];
        $log = PayLog::where('order_sn',$order->order_sn)->first();
        $log->update($data);
    }
    public function arrayToXml(array $array, SimpleXMLElement $xml = null): string {
        if ($xml === null) {
            $xml = new SimpleXMLElement('<?xml version="1.0"?><root></root>');
        }
    
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item'; // 如果数组是索引数组，则使用 'item' 作为标签名
                }
                $subnode = $xml->addChild($key);
                arrayToXml($value, $subnode);
            } else {
                $xml->addChild($key, htmlspecialchars($value));
            }
        }
    
        return $xml->asXML();
    }

}
